/**
 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
 */
// 此处第二个参数vm，就是我们在页面使用的this，你可以通过vm获取vuex等操作
import {
	Base64
} from '@/common/base64.js'
const install = (Vue, vm) => {
	// 通用请求头设定
	const ajaxHeader = 'x-ajax';
	const sessionIdHeader = 'Authorization';
	const rememberMeHeader = 'x-remember';
	const sessionTokenHeader = 'Blade-Auth';
	// 请求参数默认配置
	Vue.prototype.$u.http.setConfig({
		baseUrl: vm.vuex_config.baseUrl,
		originalData: true,
		// 默认头部，http2约定header名称统一小写 aidex
		header: {
			'content-type': 'application/x-www-form-urlencoded',
			'x-requested-with': 'XMLHttpRequest'
		}
	});
	let isRefreshing = false,
		requestQueue = []
	// 请求拦截，配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (req) => {
		if (!req.header) {
			req.header = [];
		}

		// 默认指定返回 JSON 数据
		if (!req.header[ajaxHeader]) {
			req.header[ajaxHeader] = 'json';
		}
		// 设定传递 Token 认证参数 aidex
		if (!req.header[sessionIdHeader] && vm.vuex_accessToken) {
			req.header[sessionTokenHeader] = 'bearer ' + vm.vuex_accessToken;
		}
		//设置了authorization 头为false时不需要增加这个头部，否则会报401
		if(req.header["authorization"]!=false){
			req.header[sessionIdHeader] = `Basic ${Base64.encode(`${vm.vuex_config.clientId}:${vm.vuex_config.clientSecret}`)}`
		}

		// 为节省流量，记住我数据不是每次都发送的，当会话失效后，尝试重试登录 aidex
		if (!req.header[rememberMeHeader] && vm.vuex_remember && req.remember) {
			req.header[rememberMeHeader] = vm.vuex_remember;
			req.remember = false;
		}
		if (vm.vuex_accessToken && check(vm.vuex_expiresIn)) {
		   // 一次进入一个刷新token
		  if (!isRefreshing) {
				isRefreshing = true
				// 刷新token的请求方法 是基于promise 封装的一个请求方法
				let headers = {"Tenant-Id": vm.vuex_config.tenantId,"Dept-Id": vm.vuex_deptId,"Role-Id": vm.vuex_roleId};
				let params= {"tenantId":vm.vuex_config.tenantId,"refresh_token":vm.vuex_refreshToken,"grant_type": "refresh_token","scope": "all"};
				vm.$u.post(vm.vuex_config.baseUrl+'/api/blade-auth/oauth/token', params,headers).then(res => {
					vm.setToken(vm, res);
					requestQueue.forEach(cb => cb(res.access_token));
					isRefreshing = false
					requestQueue = [];  // 清空请求队列
				});
			}
		  }
		  const request = new Promise(resolve => {
			requestQueue.push(token => {
			  req.header[sessionTokenHeader] = 'bearer ' + token;
			  resolve(req);
			});
		  });
		// console.log('request', req);
		return req;
	}

	// 响应拦截，判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = async (res, req) => {
		// console.log('response', res);
		let data = res.data;
		if (!res && !(data)) {
			vm.$u.toast('未连接到服务器')
			return false;
		}
		if (res.data.code == 401) {
			let loginSource = vm.vuex_loginSource;
			vm.removeToken(vm)
			if (loginSource && loginSource==='1') {
				window.location.href=this.vuex_config.authUrl+"/cas_ticket";
			}else if(loginSource==='2'){
				window.location.href=this.vuex_config.authUrl+"/wechat_mp";
			} else {
				//保存当前页面
				vm.fungoPreviousPage();
				uni.reLaunch({
					url: '/pages/sys/login/index'
				})
			}
			return false;
		}
		//如果是登录时，有返回token信息
		if (typeof data === 'object' && !(data instanceof Array)) {
			if (data != null && data.access_token) {
				vm.setToken(vm, data);
			}
		}
		if (res.header && res.header[rememberMeHeader]) {
			let remember = res.header[rememberMeHeader];
			if (remember && remember != 'deleteMe') {
				vm.$u.vuex('vuex_remember', remember);
			} else {
				vm.$u.vuex('vuex_remember', '');
			}
		}

		return data;
	}

	// 封装 get text 请求
	vm.$u.getText = (url, data = {}, header = {}) => {
		return vm.$u.http.request({
			dataType: 'text',
			method: 'GET',
			url,
			header,
			data
		})
	}

	// 封装 post json 请求
	vm.$u.postJson = (url, data = {}, header = {}) => {
		header['content-type'] = 'application/json';
		return vm.$u.http.request({
			url,
			method: 'POST',
			header,
			data
		})
	}
	function check(time) {
		var time1 = new Date(time)
		var date2=new Date();
		return time1.getTime() - date2.getTime()-(60*60*1000)<0 ? true:false;
	}
}

export default {
	install
}
